/**
 * 小红书平台集成服务
 * 提供内容同步、用户识别、笔记发布和效果追踪功能
 */

import { get, post } from '@/utils/request';
import { handleError } from '@/utils/errorHandler';
import { cache } from '@/utils/cacheManager';

// 小红书用户信息接口
interface XiaohongshuUser {
  user_id: string;
  nickname: string;
  avatar: string;
  desc: string;
  gender: number; // 0-未知 1-男 2-女
  follows: number; // 关注数
  fans: number; // 粉丝数
  interaction: number; // 获赞与收藏数
  notes: number; // 笔记数
  is_verified: boolean; // 是否认证
  verification_type: string; // 认证类型
}

// 小红书笔记信息接口
interface XiaohongshuNote {
  note_id: string;
  title: string;
  desc: string;
  type: 'normal' | 'video'; // 笔记类型
  cover: string;
  images?: string[];
  video_url?: string;
  tags: string[];
  topics: string[];
  time: number; // 发布时间戳
  last_update_time: number;
  interact_info: {
    liked_count: number; // 点赞数
    collected_count: number; // 收藏数
    comment_count: number; // 评论数
    share_count: number; // 分享数
  };
  author: XiaohongshuUser;
}

// 发布笔记参数接口
interface PublishNoteParams {
  title: string;
  desc: string;
  type: 'normal' | 'video';
  images?: string[];
  video_url?: string;
  tags?: string[];
  topics?: string[];
  location?: {
    name: string;
    address: string;
    latitude: number;
    longitude: number;
  };
  privacy_setting?: 'public' | 'friends' | 'private';
}

// 小红书API响应接口
interface XiaohongshuApiResponse<T = any> {
  code: number;
  success: boolean;
  msg: string;
  data: T;
}

// 数据分析接口
interface NoteAnalytics {
  note_id: string;
  date: string;
  view_count: number;
  like_count: number;
  collect_count: number;
  comment_count: number;
  share_count: number;
  profile_view: number;
  follow_count: number;
}

// 热门话题接口
interface HotTopic {
  topic_id: string;
  topic_name: string;
  desc: string;
  note_count: number;
  view_count: number;
  is_hot: boolean;
}

/**
 * 小红书平台服务类
 */
class XiaohongshuService {
  private readonly baseUrl = 'https://edith.xiaohongshu.com';
  private readonly apiKey: string;
  private readonly apiSecret: string;
  private accessToken: string = '';
  
  constructor() {
    this.apiKey = process.env.XIAOHONGSHU_API_KEY || '';
    this.apiSecret = process.env.XIAOHONGSHU_API_SECRET || '';
    this.loadToken();
  }
  
  /**
   * 加载存储的token
   */
  private loadToken(): void {
    try {
      const token = cache.get('xiaohongshu_token', 'local');
      if (token) {
        this.accessToken = token as string;
      }
    } catch (error) {
      console.warn('Failed to load xiaohongshu token:', error);
    }
  }
  
  /**
   * 保存token到本地存储
   */
  private saveToken(token: string): void {
    try {
      this.accessToken = token;
      cache.set('xiaohongshu_token', token, {
        storage: 'local',
        expireTime: 24 * 60 * 60 * 1000 // 24小时
      });
    } catch (error) {
      console.error('Failed to save xiaohongshu token:', error);
    }
  }
  
  /**
   * 生成授权登录URL
   */
  generateAuthUrl(redirectUri: string, state?: string): string {
    const params = new URLSearchParams({
      client_id: this.apiKey,
      response_type: 'code',
      scope: 'user_info,note_publish,note_data',
      redirect_uri: redirectUri,
      state: state || Date.now().toString()
    });
    
    return `${this.baseUrl}/api/oauth/authorize?${params.toString()}`;
  }
  
  /**
   * 通过授权码获取访问令牌
   */
  async getAccessToken(code: string, redirectUri: string): Promise<string> {
    try {
      const response = await post('/api/xiaohongshu/oauth/token', {
        client_id: this.apiKey,
        client_secret: this.apiSecret,
        code: code,
        redirect_uri: redirectUri,
        grant_type: 'authorization_code'
      });
      
      if (response.data.success) {
        const { access_token } = response.data.data;
        this.saveToken(access_token);
        return access_token;
      } else {
        throw new Error(response.data.msg);
      }
    } catch (error) {
      handleError(error, {
        showToast: true,
        logToConsole: true
      });
      throw error;
    }
  }
  
  /**
   * 获取用户信息
   */
  async getUserInfo(userId?: string): Promise<XiaohongshuUser> {
    try {
      const cacheKey = `xiaohongshu_user_${userId || 'current'}`;
      
      return await cache.getOrSet(
        cacheKey,
        async () => {
          const response = await get('/api/xiaohongshu/user/info', {
            access_token: this.accessToken,
            user_id: userId
          });
          
          if (response.data.success) {
            return response.data.data;
          } else {
            throw new Error(response.data.msg);
          }
        },
        {
          storage: 'local',
          expireTime: 30 * 60 * 1000 // 30分钟
        }
      );
    } catch (error) {
      handleError(error, {
        showToast: true,
        logToConsole: true
      });
      throw error;
    }
  }
  
  /**
   * 获取用户笔记列表
   */
  async getUserNotes(userId: string, cursor: string = '', num: number = 20): Promise<{
    notes: XiaohongshuNote[];
    cursor: string;
    has_more: boolean;
  }> {
    try {
      const response = await get('/api/xiaohongshu/user/notes', {
        access_token: this.accessToken,
        user_id: userId,
        cursor: cursor,
        num: num
      });
      
      if (response.data.success) {
        return response.data.data;
      } else {
        throw new Error(response.data.msg);
      }
    } catch (error) {
      handleError(error, {
        showToast: true,
        logToConsole: true
      });
      throw error;
    }
  }
  
  /**
   * 发布笔记到小红书
   */
  async publishNote(params: PublishNoteParams): Promise<{ note_id: string }> {
    try {
      const response = await post('/api/xiaohongshu/note/publish', {
        access_token: this.accessToken,
        ...params
      });
      
      if (response.data.success) {
        return response.data.data;
      } else {
        throw new Error(response.data.msg);
      }
    } catch (error) {
      handleError(error, {
        showToast: true,
        logToConsole: true
      });
      throw error;
    }
  }
  
  /**
   * 获取笔记详情
   */
  async getNoteDetail(noteId: string): Promise<XiaohongshuNote> {
    try {
      const cacheKey = `xiaohongshu_note_${noteId}`;
      
      return await cache.getOrSet(
        cacheKey,
        async () => {
          const response = await get('/api/xiaohongshu/note/detail', {
            access_token: this.accessToken,
            note_id: noteId
          });
          
          if (response.data.success) {
            return response.data.data;
          } else {
            throw new Error(response.data.msg);
          }
        },
        {
          storage: 'local',
          expireTime: 15 * 60 * 1000 // 15分钟
        }
      );
    } catch (error) {
      handleError(error, {
        showToast: true,
        logToConsole: true
      });
      throw error;
    }
  }
  
  /**
   * 获取笔记数据分析
   */
  async getNoteAnalytics(noteIds: string[], dateRange: 'yesterday' | '7days' | '30days' = '7days'): Promise<NoteAnalytics[]> {
    try {
      const cacheKey = `xiaohongshu_analytics_${noteIds.join(',')}_${dateRange}`;
      
      return await cache.getOrSet(
        cacheKey,
        async () => {
          const response = await post('/api/xiaohongshu/data/note_analytics', {
            access_token: this.accessToken,
            note_ids: noteIds,
            date_range: dateRange
          });
          
          if (response.data.success) {
            return response.data.data.analytics || [];
          } else {
            throw new Error(response.data.msg);
          }
        },
        {
          storage: 'local',
          expireTime: 60 * 60 * 1000 // 1小时
        }
      );
    } catch (error) {
      handleError(error, {
        showToast: true,
        logToConsole: true
      });
      throw error;
    }
  }
  
  /**
   * 搜索笔记
   */
  async searchNotes(keyword: string, sort: 'general' | 'time' | 'popularity' = 'general', page: number = 1): Promise<{
    notes: XiaohongshuNote[];
    total: number;
    has_more: boolean;
  }> {
    try {
      const cacheKey = `xiaohongshu_search_${keyword}_${sort}_${page}`;
      
      return await cache.getOrSet(
        cacheKey,
        async () => {
          const response = await get('/api/xiaohongshu/search/notes', {
            access_token: this.accessToken,
            keyword: keyword,
            sort: sort,
            page: page
          });
          
          if (response.data.success) {
            return response.data.data;
          } else {
            throw new Error(response.data.msg);
          }
        },
        {
          storage: 'local',
          expireTime: 15 * 60 * 1000 // 15分钟
        }
      );
    } catch (error) {
      handleError(error, {
        showToast: true,
        logToConsole: true
      });
      throw error;
    }
  }
  
  /**
   * 获取热门话题
   */
  async getHotTopics(category?: string): Promise<HotTopic[]> {
    try {
      const cacheKey = `xiaohongshu_hot_topics_${category || 'all'}`;
      
      return await cache.getOrSet(
        cacheKey,
        async () => {
          const response = await get('/api/xiaohongshu/topics/hot', {
            access_token: this.accessToken,
            category: category
          });
          
          if (response.data.success) {
            return response.data.data.topics || [];
          } else {
            throw new Error(response.data.msg);
          }
        },
        {
          storage: 'local',
          expireTime: 60 * 60 * 1000 // 1小时
        }
      );
    } catch (error) {
      handleError(error, {
        showToast: true,
        logToConsole: true
      });
      throw error;
    }
  }
  
  /**
   * 上传图片
   */
  async uploadImage(imageFile: File | Blob): Promise<{ image_url: string }> {
    try {
      const formData = new FormData();
      formData.append('file', imageFile);
      formData.append('access_token', this.accessToken);
      
      const response = await post('/api/xiaohongshu/upload/image', formData, {
        header: {
          'Content-Type': 'multipart/form-data'
        }
      });
      
      if (response.data.success) {
        return response.data.data;
      } else {
        throw new Error(response.data.msg);
      }
    } catch (error) {
      handleError(error, {
        showToast: true,
        logToConsole: true
      });
      throw error;
    }
  }
  
  /**
   * 上传视频
   */
  async uploadVideo(videoFile: File | Blob): Promise<{ video_url: string; cover_url: string }> {
    try {
      const formData = new FormData();
      formData.append('file', videoFile);
      formData.append('access_token', this.accessToken);
      
      const response = await post('/api/xiaohongshu/upload/video', formData, {
        header: {
          'Content-Type': 'multipart/form-data'
        }
      });
      
      if (response.data.success) {
        return response.data.data;
      } else {
        throw new Error(response.data.msg);
      }
    } catch (error) {
      handleError(error, {
        showToast: true,
        logToConsole: true
      });
      throw error;
    }
  }
  
  /**
   * 同步用户数据到本地数据库
   */
  async syncUserData(userId: string): Promise<void> {
    try {
      const userInfo = await this.getUserInfo(userId);
      const notes = await this.getUserNotes(userId, '', 100);
      
      // 同步到本地数据库
      await post('/api/xiaohongshu/sync/user', {
        user_info: userInfo,
        notes: notes.notes
      });
      
      console.log('Xiaohongshu user data synced successfully');
    } catch (error) {
      handleError(error, {
        showToast: true,
        logToConsole: true
      });
      throw error;
    }
  }
  
  /**
   * 批量发布内容到小红书
   */
  async batchPublish(contents: Array<{
    title: string;
    desc: string;
    type: 'normal' | 'video';
    images?: string[];
    video_url?: string;
    tags?: string[];
    schedule_time?: number;
  }>): Promise<Array<{ note_id: string; success: boolean; error?: string }>> {
    const results = [];
    
    for (const content of contents) {
      try {
        if (content.schedule_time && content.schedule_time > Date.now()) {
          // 定时发布
          await this.schedulePublish(content, content.schedule_time);
          results.push({ note_id: '', success: true });
        } else {
          // 立即发布
          const result = await this.publishNote({
            title: content.title,
            desc: content.desc,
            type: content.type,
            images: content.images,
            video_url: content.video_url,
            tags: content.tags
          });
          results.push({ note_id: result.note_id, success: true });
        }
      } catch (error) {
        results.push({ 
          note_id: '', 
          success: false, 
          error: error instanceof Error ? error.message : 'Unknown error'
        });
      }
    }
    
    return results;
  }
  
  /**
   * 定时发布内容
   */
  private async schedulePublish(content: {
    title: string;
    desc: string;
    type: 'normal' | 'video';
    images?: string[];
    video_url?: string;
    tags?: string[];
  }, scheduleTime: number): Promise<void> {
    // 将定时发布任务存储到队列中
    await post('/api/xiaohongshu/schedule', {
      content: content,
      schedule_time: scheduleTime,
      access_token: this.accessToken
    });
  }
  
  /**
   * 检查token是否有效
   */
  async checkTokenValid(): Promise<boolean> {
    try {
      await this.getUserInfo();
      return true;
    } catch (error) {
      return false;
    }
  }
  
  /**
   * 获取账号统计数据
   */
  async getAccountStats(): Promise<{
    fans: number;
    follows: number;
    notes: number;
    total_likes: number;
    total_collects: number;
  }> {
    try {
      const userInfo = await this.getUserInfo();
      const notes = await this.getUserNotes(userInfo.user_id, '', 100);
      
      const totalLikes = notes.notes.reduce((sum, note) => {
        return sum + note.interact_info.liked_count;
      }, 0);
      
      const totalCollects = notes.notes.reduce((sum, note) => {
        return sum + note.interact_info.collected_count;
      }, 0);
      
      return {
        fans: userInfo.fans,
        follows: userInfo.follows,
        notes: userInfo.notes,
        total_likes: totalLikes,
        total_collects: totalCollects
      };
    } catch (error) {
      handleError(error, {
        showToast: true,
        logToConsole: true
      });
      throw error;
    }
  }
  
  /**
   * 获取内容推荐
   */
  async getContentRecommendations(category: string, tags: string[]): Promise<{
    trending_topics: string[];
    suggested_tags: string[];
    optimal_time: string;
    content_tips: string[];
  }> {
    try {
      const cacheKey = `xiaohongshu_recommendations_${category}_${tags.join(',')}`;
      
      return await cache.getOrSet(
        cacheKey,
        async () => {
          const response = await post('/api/xiaohongshu/content/recommendations', {
            access_token: this.accessToken,
            category: category,
            tags: tags
          });
          
          if (response.data.success) {
            return response.data.data;
          } else {
            throw new Error(response.data.msg);
          }
        },
        {
          storage: 'local',
          expireTime: 2 * 60 * 60 * 1000 // 2小时
        }
      );
    } catch (error) {
      handleError(error, {
        showToast: true,
        logToConsole: true
      });
      throw error;
    }
  }
}

// 创建单例实例
const xiaohongshuService = new XiaohongshuService();

// 导出服务实例和便捷方法
export { xiaohongshuService, XiaohongshuService };
export type { XiaohongshuUser, XiaohongshuNote, PublishNoteParams, NoteAnalytics, HotTopic };

// 便捷方法导出
export const {
  generateAuthUrl,
  getAccessToken,
  getUserInfo,
  getUserNotes,
  publishNote,
  getNoteDetail,
  getNoteAnalytics,
  searchNotes,
  getHotTopics,
  uploadImage,
  uploadVideo,
  syncUserData,
  batchPublish,
  checkTokenValid,
  getAccountStats,
  getContentRecommendations
} = xiaohongshuService;

export default xiaohongshuService;